/**
 * Copyright (c) 2019-2029, wwww.kiwipeach.cn (liuburu@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cn.kiwipeach.blog.service.impl;

import cn.kiwipeach.blog.base.AjaxResponse;
import cn.kiwipeach.blog.database.domain.CategoryTreeVO;
import cn.kiwipeach.blog.database.generator.domain.BlogCategory;
import cn.kiwipeach.blog.database.mapper.CustomBlogCategoryMapper;
import cn.kiwipeach.blog.service.IBlogCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * 分类 服务实现类
 *
 * @author kiwipeach
 * @since 1.0
 */
@Service
public class BlogCategoryServiceImpl extends ServiceImpl<CustomBlogCategoryMapper, BlogCategory> implements IBlogCategoryService {

    @Autowired
    private CustomBlogCategoryMapper customBlogCategoryMapper;

    @Override
    public AjaxResponse<CategoryTreeVO> queryBlogCategoryTree() {
        // 构建好的分类对象(即children属性初始化)
        CategoryTreeVO rootNode = new CategoryTreeVO().setId("").setName("root");
        List<CategoryTreeVO> categoryContainer = new ArrayList<>(Arrays.asList(rootNode));
        List<CategoryTreeVO> categoryTreeVos = customBlogCategoryMapper.selectCategoryTree();
        for (CategoryTreeVO category : categoryTreeVos) {
            buildCategoryTree(category, categoryContainer);
            // 初始化统计值字段
            String countStr = getCountDescription(category.getCount());
            category.setName(category.getName() + countStr);
        }
        return AjaxResponse.success(rootNode);
    }

    /**
     * 获取统计结果格式化字符串
     *
     * @param count 统计数
     * @return 返回统计格式字符模板
     */
    private String getCountDescription(String count) {
        return !StringUtils.isEmpty(count) ? String.format("(%s)", count) : "";
    }

    private void buildCategoryTree(CategoryTreeVO currentNode, List<CategoryTreeVO> categoryContainer) {
        // 查找重构当前节点的父节点，当前节点做“儿子”（循环遍历所有节点，直到找到“爹”为止）
        refatorCategoryParent(currentNode, categoryContainer);
        // 查找重构当前节点的子节点，当前节点做“爹”（循环遍历所有没有爹的小孩，进行“认养”）
        refatorCategoryChildren(currentNode, categoryContainer);
    }

    private void refatorCategoryParent(CategoryTreeVO currentNode, List<CategoryTreeVO> categoryContainer) {
        Iterator<CategoryTreeVO> iterator = categoryContainer.iterator();
        while (iterator.hasNext()) {
            CategoryTreeVO next = iterator.next();
            // currentNode：{id:101,parentId:10}   next：{id:10}
            if (currentNode.getParentId().equals(next.getId())) {
                next.getChildren().add(currentNode);
                break;
            }
        }
    }

    private void refatorCategoryChildren(CategoryTreeVO currentNode, List<CategoryTreeVO> categoryContainer) {
        Iterator<CategoryTreeVO> iterator = categoryContainer.iterator();
        while (iterator.hasNext()) {
            CategoryTreeVO next = iterator.next();
            // currentNode：10   next：{id:101,parentId:10}
            if (currentNode.getId().equals(next.getParentId())) {
                currentNode.getChildren().add(next);
            }
        }
        categoryContainer.add(currentNode);
    }

}
